﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
#if WP7
using nRoute.Behaviors.Interactivity;
#endif

namespace nRoute.Samples.Netflix.Behaviors
{
    public class BoolValueOpacityBehavior
#if WP7
        : BindableBehavior<FrameworkElement>
#else
        : Behavior<UIElement>
#endif
    {
        private const double VISIBLE = 1d;
        private const double COLLAPSED = 0d;

        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(bool), typeof(BoolValueOpacityBehavior),
            new PropertyMetadata(false, new PropertyChangedCallback(OnValueChanged)));

        private bool _negate;

#region Properties

        [Category("Common Properties")]
        public bool Value
        {
            get { return Convert.ToBoolean(GetValue(ValueProperty)); }
            set { SetValue(ValueProperty, value); }
        }

#if WP7

        [Category("Common Properties")]
#if (!WP7)
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
#endif
        public Binding ValueBinding
        {
            get { return GetBinding(ValueProperty); }
            set { SetBinding<bool>(ValueProperty, value); }
        }

#endif

        [Category("Common Properties")]
        public bool Negate
        {
            get { return _negate; }
            set { _negate = value; }
        }

#endregion

#region Trigger Related

        protected override void OnAttached()
        {
            base.OnAttached();
            UpdateOpacity(Value);
        }

#endregion

#region Handlers

        private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((BoolValueOpacityBehavior)d).UpdateOpacity(Convert.ToBoolean(e.NewValue));
        }

        private void UpdateOpacity(bool value)
        {
            if (this.AssociatedObject == null) return;

            var _opacity = value ? VISIBLE : COLLAPSED;
            if (Negate) _opacity = value ? COLLAPSED : VISIBLE;
            this.AssociatedObject.Opacity = _opacity;
        }

#endregion

    }
}
